<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文件管理</el-breadcrumb-item>
      <el-breadcrumb-item>文件发布</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-form label-width="100px" ref="formRef" :model="form" :rules="formRules">
        <el-form-item label="章节：" prop="chapterId">
          <el-select v-model="form.chapterId">
            <el-option v-for="item in chapters" :key="item.chapterId" :value="item.chapterId" :label="item.chapterName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称：" prop="officeName">
          <el-input v-model="form.officeName"></el-input>
        </el-form-item>
        <el-form-item label="文件：" prop="officeUrl">
          <el-upload
            ref="uploadOfficeRef"
            action="http://localhost:8081/api/admin/office/uploadOffice"
            :headers="headers"
            accept=".ppt, .pptx, .docx, .dox, .pdf"
            :before-upload="checkFileType"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-preview="preview"
            :on-remove="deleteOffice"
            :limit="1">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-input v-show="false" v-model="form.officeUrl"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import officeApi from '@/api/office'

var token = sessionStorage.getItem('token')

export default {
  data() {
    return {
      headers: {
        token: token
      },
      form: {
        level: undefined,
        chapterId: undefined,
        officeName: '',
        officeUrl: null,
        officeSourceName: null
      },
      formRules: {
        chapterId: [
          { required: true, message: '请选择章节', trigger: 'change' }
        ],
        officeName: [
          { required: true, message: '请输入名称' }
        ],
        officeUrl: [
          { required: true, message: '请上传文件' }
        ],
      },
    }
  },
  props: {
    mainLevel: {
      type: Number
    }
  },
  watch: {
    mainLevel() {
      this.form.level = this.mainLevel
      this.resetForm()
    }
  },
  created() {
    this.form.level = this.mainLevel
  },
  methods: {
    preview() {
      window.open('https://view.xdocin.com/view?src=' + this.form.officeUrl, '_blank')
    },
    deleteOffice() {
      let data = {
        officeSourceName: this.form.officeSourceName
      }
      officeApi.deleteOffice(data).then(re => {
        if (re.code === this.ok.code) {
          this.form.officeSourceName = null
          this.form.officeUrl = null
        }
      })
    },
    // 上传前
    checkFileType(file) {
      const fileName = file.name
      const typeArr = ['.doc', '.docx', '.ppt', '.pptx', '.pdf']
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      if (typeArr.indexOf(fileType) === -1) {
        this.$message.error('请上传符合格式的文件')
        return false
      }
    },
    // 上传成功
    uploadSuccess(data, file, fileList) {
      if (data.code === 401) {
        this.$message.error(data.message)
        this.$router.replace('/login')
        return
      }
      this.form.officeUrl = data.response.officeUrl
      this.form.officeSourceName = data.response.officeSourceName
    },
    uploadError() {
      this.$message.error("上传失败")
    },
    submitForm() {
      let _this = this
      this.$refs.formRef.validate((valid) => {
        if (!valid) return false
        officeApi.create(this.form).then(re => {
          if (re.code === _this.ok.code) {
            _this.$router.push('/office/list')
          } else {
            _this.$message.error(re.message)
          }
        })
      })
    },
    resetForm() {
      // 如果有文件url 则删除文件
      this.deleteOffice()
      this.$refs.formRef.resetFields()
      this.$refs['uploadOfficeRef'].clearFiles();
    }
  },
  computed: {
    ...mapState('chapter', {
      chapters: state => state.chapters
    }),
    ...mapState('resCode', {
      ok: state => state.OK
    }),
  }
}
</script>

<style lang="less" scoped>

</style>